package common.tool.box.web.controller.common;

import common.tool.box.common.config.CommonToolBoxConfig;
import common.tool.box.common.constant.Constants;
import common.tool.box.common.core.controller.BaseController;
import common.tool.box.common.core.domain.AjaxResult;
import common.tool.box.common.utils.StringUtils;
import common.tool.box.common.utils.file.FileUploadUtils;
import common.tool.box.common.utils.file.FileUtils;
import common.tool.box.framework.config.ServerConfig;
import common.tool.box.framework.web.service.SysFileService;
import common.tool.box.system.domain.SysUserFile;
import common.tool.box.system.service.impl.SysUserFileServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 通用请求处理
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/common")
@Api(tags = "common")
public class CommonController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private SysUserFileServiceImpl sysUserFileService;

    private static final String FILE_DELIMETER = ",";

    @Autowired
    private SysFileService fileService;

    /**
     * 拼接图片url
     */
    @ApiOperation("拼接图片url")
    @ApiImplicitParam(name = "fileName", value = "文件名", dataType = "String", dataTypeClass = String.class)
    @GetMapping("/getUrl")
    public String commonGetPicUrl(String fileName)
    {
        return serverConfig.getUrl() + fileName;
    }

    /**
     * 通用下载请求
     * 
     * @param fileName 文件名称
     * @param delete 是否删除
     */
    @ApiOperation("通用下载请求")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "fileName", value = "文件名", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "delete", value = "是否删除", dataType = "Boolean", dataTypeClass = Boolean.class)
    })
    @GetMapping("/download")
    public void commonFileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request)
    {
        try
        {
            SysUserFile sysUserFile = new SysUserFile();
            sysUserFile.setFilePath(fileName);
            List<SysUserFile> sysUserFiles = sysUserFileService.selectSysUserFileList(sysUserFile);
            if (sysUserFiles != null && sysUserFiles.size() > 0) {
                sysUserFile = sysUserFiles.get(0);
            } else {
                throw new Exception("文件不存在");
            }
            // fileName需要去掉开头的/upload/
            if (StringUtils.isNotEmpty(fileName) && fileName.startsWith(Constants.RESOURCE_PREFIX))
            {
                fileName = fileName.substring(Constants.RESOURCE_PREFIX.length());
            }
            if (!FileUtils.checkAllowDownload(fileName))
            {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String filePath = FileUploadUtils.getAbsoluteFile(CommonToolBoxConfig.getProfile() ,fileName).getAbsolutePath();

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            // 文件名取最后一个 / 之后的
            String[] pathArray = fileName.split("/");
            fileName = pathArray[pathArray.length - 1];
            FileUtils.setAttachmentResponseHeader(response, sysUserFile.getOriginalName());
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete)
            {
                // 取出fileName最后第二个.和最后一个.之间的字符串
                String[] fileNameArray = fileName.split("\\.");
                String fileId = fileNameArray[fileNameArray.length - 2];
                sysUserFileService.deleteSysUserFileByFileIds(Collections.singletonList(fileId));
                FileUtils.deleteFile(filePath);
            }
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 通用上传请求（单个）
     */
    @ApiOperation("通用上传请求（单个）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "文件", dataType = "MultipartFile", dataTypeClass = MultipartFile.class)
    })
    @PostMapping("/upload")
    public AjaxResult commonUploadFile(MultipartFile file) throws Exception
    {
        try
        {
            if (fileService.getUserFilesInfo().getIsOverLimit()) {
                return AjaxResult.error("上传失败，文件数量超出限制");
            }
            // 上传文件路径
            String filePath = CommonToolBoxConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            // 保存用户与文件对应关系
            sysUserFileService.insertSysUserFile(fileNameToDto(fileName, file));

            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 通用上传请求（多个）
     */
    @ApiOperation("通用上传请求（多个）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "files", value = "文件", dataType = "List", dataTypeClass = List.class)
    })
    @PostMapping("/uploads")
    public AjaxResult commonUploadFiles(List<MultipartFile> files) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = CommonToolBoxConfig.getUploadPath();
            List<String> urls = new ArrayList<String>();
            List<String> fileNames = new ArrayList<String>();
            List<String> newFileNames = new ArrayList<String>();
            List<String> originalFilenames = new ArrayList<String>();
            for (MultipartFile file : files)
            {
                if (fileService.getUserFilesInfo().getIsOverLimit()) {
                    return AjaxResult.error("上传失败，文件数量超出限制");
                }
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                // 保存用户与文件对应关系
                sysUserFileService.insertSysUserFile(fileNameToDto(fileName, file));
                String url = serverConfig.getUrl() + fileName;
                urls.add(url);
                fileNames.add(fileName);
                newFileNames.add(FileUtils.getName(fileName));
                originalFilenames.add(file.getOriginalFilename());
            }
            AjaxResult ajax = AjaxResult.success();
            ajax.put("urls", StringUtils.join(urls, FILE_DELIMETER));
            ajax.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER));
            ajax.put("newFileNames", StringUtils.join(newFileNames, FILE_DELIMETER));
            ajax.put("originalFilenames", StringUtils.join(originalFilenames, FILE_DELIMETER));
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 本地资源通用下载
     */
    @ApiOperation("本地资源通用下载")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "resource", value = "本地资源", dataType = "String", dataTypeClass = String.class)
    })
    @GetMapping("/download/resource")
    public void commonResourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
            throws Exception
    {
        try
        {
            if (!FileUtils.checkAllowDownload(resource))
            {
                throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", resource));
            }
            // 本地资源路径
            String localPath = CommonToolBoxConfig.getProfile();
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }

    public SysUserFile fileNameToDto(String fileName, MultipartFile file) {
        // 上传完成后存储用户与文件对应关系
        SysUserFile sysUserFile = new SysUserFile();
        // 新文件名
        String newFileName = FileUtils.getName(fileName);
        String[] partName = newFileName.split("\\.");
        String seqId = partName[partName.length - 2];

        sysUserFile.setUserId(getUserId());
        sysUserFile.setUserName(getUsername());
        sysUserFile.setFileId(seqId);
        sysUserFile.setFilePath(fileName);
        sysUserFile.setOriginalName(file.getOriginalFilename());
        sysUserFile.setNewName(newFileName);
        sysUserFile.setFileSize(1.0 * file.getSize() / Constants.FILE_SIZE_ONE_KB);
        return sysUserFile;
    }
}
